from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import Posts, User, SportRecords, Tags
import uuid
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.h_result import HResult
from datetime import datetime
from utils.utils import query_page_list, to_beijing_time

bp = Blueprint('posts', __name__, url_prefix='/posts/')

class AddPost(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        title = data.get('title')
        content = data.get('content')
        current_user = get_jwt_identity()
        
        if not title or not content:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        
        post = Posts(
            id=str(uuid.uuid4()),
            user_id=user.id,
            title=title,
            content=content,
            create_time=to_beijing_time(datetime.utcnow()),
            update_time=to_beijing_time(datetime.utcnow())
        )
        
        if 'record_id' in data:
            post.record_id = data['record_id']
            
        db.session.add(post)
        db.session.commit()
        return HResult().get_result('success', '发帖成功!', post.to_dict())

class DeletePost(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        post_ids = data['ids']
        current_user = get_jwt_identity()
        user = User.query.filter_by(name=current_user).first()
        
        for post_id in post_ids:
            post = Posts.query.filter_by(id=post_id, del_flag='1').first()
            if post and post.user_id == user.id:
                # 改为逻辑删除
                post.del_flag = '0'
                
        db.session.commit()
        return HResult().get_result('success', '删除成功!')

class UpdatePost(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        post_id = data['id']
        current_user = get_jwt_identity()
        
        post = Posts.query.filter_by(id=post_id).first()
        if not post:
            return HResult().get_result('error', '帖子不存在!')
            
        user = User.query.filter_by(name=current_user).first()
        if post.user_id != user.id:
            return HResult().get_result('error', '无权修改此帖子!')
            
        for key, value in data.items():
            if key not in ['id', 'user_id', 'create_time']:
                setattr(post, key, value)
        
        post.update_time = to_beijing_time(datetime.utcnow())
        db.session.commit()
        return HResult().get_result('success', '修改成功!')

class PostInfo(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        post_id = request.args.get('id')
        post = Posts.query.filter_by(id=post_id, del_flag='1').first()
        
        if not post:
            return HResult().get_result('error', '帖子不存在!')
            
        data = post.to_dict()
        # 添加关联数据
        data['user'] = post.user.to_dict()

        if post.record:
            data['record'] = post.record.to_dict()
            
        # 添加标签详情
        if post.tags:
            tag_ids = post.tags.split(',')
            tags = Tags.query.filter(Tags.id.in_(tag_ids)).all()
            data['tags'] = [tag.to_dict() for tag in tags]
        else:
            data['tags'] = []

        return HResult().get_result('success', data=data)

class QueryAllPosts(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        
        # 添加 del_flag 条件
        if 'params' not in data:
            data['params'] = {}
        data['params']['del_flag'] = '1'
        
        # 使用分页查询
        result = query_page_list(
            model_class=Posts,
            page_size=data['pageSize'],
            page_no=data['pageNo'],
            params=data['params'],
            order_by=Posts.create_time.desc()
        )
        
        # 对结果中的每条记录添加用户名
        # for item in result['list']:
        #     post = Posts.query.filter_by(id=item['id']).first()
        #     item['user_name'] = post.user.name
        #     # 添加标签名称列表
        #     if post.tags:
        #         tag_ids = post.tags.split(',')
        #         tags = Tags.query.filter(Tags.id.in_(tag_ids)).all()
        #         item['tag_names'] = [tag.name for tag in tags]
        #     else:
        #         item['tag_names'] = []
        
        return HResult().get_result('success', data=result)

api = Api(bp)
api.add_resource(AddPost, '/add/', endpoint='add')
api.add_resource(DeletePost, '/delete/', endpoint='delete')
api.add_resource(UpdatePost, '/update/', endpoint='update')
api.add_resource(PostInfo, '/info/', endpoint='info')
api.add_resource(QueryAllPosts, '/list/', endpoint='list') 